package com.danton.auth.realm;

import java.util.List;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Sha1Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.danton.auth.service.UserService;
import com.danton.auth.service.impl.UserServiceImpl;
import com.danton.auth.token.LoginToken;
import com.danton.common.utils.StringUtils;
import com.danton.model.BsAdminModel;
import com.danton.model.BsPermissionModel;
import com.danton.model.BsRoleModel;
import com.jfinal.aop.Enhancer;
import com.jfinal.kit.StrKit;

public class UserAuthRealm extends AuthorizingRealm {
	protected static final Logger logger = LoggerFactory.getLogger(UserAuthRealm.class);
	private UserService userService = Enhancer.enhance(UserServiceImpl.class);//支持事务处理
	//private UserService userService = new UserServiceImpl();
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		BsAdminModel adminModel = (BsAdminModel)principals.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		System.out.println("admin_id:"+adminModel.getInt("id"));
		//添加角色
		List<BsRoleModel> rolelist = userService.findRolesByUserID(adminModel.getInt("id"));
		for (BsRoleModel bsRoleModel : rolelist) {
			authorizationInfo.addRole(bsRoleModel.getStr("code"));
			System.out.println("role_code:"+bsRoleModel.getStr("code"));
		}
        //添加权限
        List<BsPermissionModel> permissionlist = userService.findPermissionsByUserID(adminModel.getInt("id"));
        for (BsPermissionModel permissionModel : permissionlist) {
        	authorizationInfo.addStringPermission(permissionModel.getStr("resource"));
        	System.out.println("resource:"+permissionModel.getStr("resource"));
		}
        return authorizationInfo;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		LoginToken authcToken = (LoginToken) token;
		String user_name = (String) token.getPrincipal(); // 得到用户名
		String password = new String((char[]) token.getCredentials()); // 得到密码
		String from = authcToken.getFrom();

		if (StrKit.isBlank(user_name)) {
            throw new AuthenticationException("用户名不可以为空");
        }
		// 如果身份认证验证成功,返回一个 AuthenticationInfo 实现;
		BsAdminModel adminModel = userService.findByUserName(user_name);
		if (adminModel == null) {
			throw new UnknownAccountException("用户不存在"); // 如果找不到用户
		}
		if(!userService.checkLoginPermission(user_name, from)){
			 throw new AuthenticationException("没有登录权限");
		}
		int status = -1;
		if(adminModel.get("status") != null && StringUtils.isNotEmpty(String.valueOf(adminModel.get("status"))))
		{
			status = Integer.parseInt(String.valueOf(adminModel.get("status")));
		}
		if(status==1)
		{
			throw new AuthenticationException("用户已冻结");
		}
		String ip_address = adminModel.get("ip_address");
		String sha1 = new Sha1Hash(password, ip_address).toString();
		logger.debug("sha1:"+sha1);
		if (!sha1.equals(adminModel.get("password"))) {
			throw new IncorrectCredentialsException("密码错误"); // 密码错误
		}
		return new SimpleAuthenticationInfo(adminModel, password, getName());
	}

}
